<!-- 下拉搜索框：懒加载+远程模糊搜索 -->
<template>
  <!-- 注意：如果v-model绑定的是一个对象，则value-key一定要有 -->
  <el-select popper-class="my-select" placeholder="请选择商品类别" v-model="selected_category" filterable remote
    remote-show-suffix value-key="categoryId" :remote-method="searchCategorys" v-loadmore="loadmore"
    :loading="search_loading" @change="handleInputConfirm" clearable @clear="handleClear">
    <!-- 选项的label为商品类别名，value为类别ID和类别名 -->
    <el-option v-for="(item, index) in currentShowingList" :key="item.categoryId" :label="item.categoryName"
      :value="item">
    </el-option>
  </el-select>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import debounce from 'lodash/debounce';

const { proxy } = getCurrentInstance();
const selected_category = ref()
const emit = defineEmits(['confirm']);  // 调用父组件的方法
const categoryList = ref([]);
const searchResultList = ref([]);
const currentShowingList = ref([]);  // 当前正在展示的列表
const loading = ref(false);
const search_loading = ref(false);
const config = reactive({
  total: 0,  // 总的条目数
  current: 1,  // 当前页
  size: 15  // 一页的条目数
});

/**
 * 自定义一个v-loadmore指令
 */
const vLoadmore = {
  beforeMount(el, binding) {
    const dom = document.querySelector('.my-select .el-select-dropdown .el-select-dropdown__wrap'); // 获取下拉框元素
    console.log('dom:', dom);
    dom.addEventListener('scroll', (e) => { // 监听元素触底
      const condition = dom.scrollHeight - dom.scrollTop <= dom.clientHeight;
      if (condition) {
        binding.value();
      }
    });
  }
}

/**
 * 加载更多内容
 */
const loadmore = async () => {
  console.log('categoryList.length: ', categoryList.value.length, 'config.total: ', config.total);
  if (categoryList.value.length < config.total) {
    config.current++;
    console.log('reach bottom, send request');
    loading.value = true;
    await getPageOfCategoryList();
    loading.value = false;
  }
}

/**
 * 获得一页的商品类别列表
 */
const getPageOfCategoryList = async () => {
  let ret = await proxy.$api.category.getAllCategory({
    current: config.current,
    size: config.size
  });
  if (ret.status === 200) {
    config.total = ret.data.total;
    categoryList.value = categoryList.value.concat(ret.data.categoryPage);
    currentShowingList.value = categoryList.value;
  }
}

/**
 * 远程模糊搜索
 * @param {string} query 搜索的内容
 */
const searchCategorys = debounce(async (query) => {
  if (query && query.length > 0) {
    console.log("search: ", query);
    search_loading.value = true;
    let ret = await proxy.$api.category.searchCategory({ categoryName: query });
    if (ret.status === 200) {
      searchResultList.value = ret.data;
      currentShowingList.value = searchResultList.value;
    }
  } else {
    currentShowingList.value = categoryList.value;
  }
  search_loading.value = false;
}, 750)  // 防抖750ms

/**
 * 确定select的结果
 */
const handleInputConfirm = () => {
  console.log('confirm')
  if (selected_category.value && selected_category.value !== '')
    emit('confirm', selected_category.value);
}

/**
 * 清空选择后，默认采用categoryList
 */
const handleClear = () => {
  currentShowingList.value = categoryList.value;
}

onMounted(async () => {
  loading.value = true;
  await getPageOfCategoryList();
  loading.value = false;
})
</script>